package logic

import (
	"context"
	"fmt"
	"user/model/mysql"
	"user/model/redis"

	"user/userrpc/internal/svc"
	"user/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	getSms := redis.Client.Get("sendSmslogin" + in.Tel)
	if getSms.Val() != in.Smscode {
		return nil, fmt.Errorf("短信验证码不正确，请重新输入")
	}
	getImg := redis.Client.Get("captchalogin" + in.Account)
	if getImg.Val() != in.Imgcode {
		return nil, fmt.Errorf("图形验证码不正确，请重新输入")
	}
	var finduser mysql.User
	mysql.DB.Debug().Where("Account=?", in.Account).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("该账号不存在，请重新输入")
	}
	if finduser.Password != in.Password {
		return nil, fmt.Errorf("密码校验不正确，请重新输入")
	}
	mysql.DB.Debug().Find(&finduser)

	return &userrpc.UserLoginResponse{Id: int64(finduser.ID)}, nil
}
